<template>
  <el-form

      :model="addForm"
      label-width="120px"
      class="pile-form"
  >
    <!-- 充电桩信息 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="充电桩名称">
          <el-input v-model="addForm.pileName"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="充电桩编号">
          <!-- 在新增时可编辑，编辑已有数据时可视需求禁用 -->
          <el-input v-model="addForm.pileCode"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="站点id">
          <el-input v-model="addForm.stationId"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="桩类型">
          <el-select v-model="addForm.pileType" placeholder="请选择桩类型">
            <el-option label="快充" value="快充"></el-option>
            <el-option label="普通" value="普通"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="功率(kW)">
          <el-input-number v-model="addForm.pilePower" :step="0.1"></el-input-number>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="桩型号">
          <el-input v-model="addForm.pileModel"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="适合车型">
          <el-input v-model="addForm.suitableVehicle"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="电站简介">
          <v-md-editor
              v-model="addForm.pileDesc"
              height="400px"
              placeholder="请输入简介的 Markdown 内容"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="充电桩图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/upload/images"
              :file-list="addFileList"
              list-type="picture-card"
              :limit="1"
              :auto-upload="true"
              :on-success="handleUploadSuccess"
              :on-remove="handleUploadRemove"
              :on-exceed="handleExceed"
          >
            <i v-if="addFileList.length === 0" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 充电枪列表 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="充电枪列表">
          <el-table :data="addForm.chargingGuns" style="width: 100%" border>
            <el-table-column prop="gunCode" label="枪编号"/>
            <el-table-column prop="gunName" label="枪名称"/>
            <el-table-column prop="gunType" label="枪类型"/>
            <el-table-column prop="outputPower" label="功率(kW)"/>
            <el-table-column prop="remark" label="备注"/>
            <el-table-column label="操作" width="240">
              <template #default="{ row, $index }">
                <el-button
                    size="small"
                    @click="openGunDialog(row)"
                >编辑
                </el-button
                >
                <el-button
                    size="small"
                    type="danger"
                    @click="removeGun($index)"
                >删除
                </el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-button
              type="primary"
              style="margin-top: 10px"
              @click="openGunDialog()"
          >新增充电枪
          </el-button
          >
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 表单底部按钮 -->
    <div style="text-align: right; margin-top: 15px;">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="doSave">保存</el-button>
    </div>
  </el-form>

  <!-- 弹窗：新增/编辑充电枪 -->
  <el-dialog
      v-model="gunDialogVisible" title="新增充电枪"
  >
    <el-form :model="gunForm" label-width="100px" class="gun-form">
      <el-form-item label="枪编号">
        <el-input
            v-model="gunForm.gunCode"
        ></el-input>
      </el-form-item>

      <el-form-item label="枪名称">
        <el-input v-model="gunForm.gunName"></el-input>
      </el-form-item>

      <el-form-item label="枪类型">
        <el-select v-model="gunForm.gunType" placeholder="请选择枪类型">
          <el-option label="直流" value="直流"></el-option>
          <el-option label="交流" value="交流"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="功率(kW)">
        <el-input-number v-model="gunForm.outputPower" :step="0.1"></el-input-number>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="gunForm.remark"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"  @click="saveGun(addForm.chargingGuns)">确定</el-button>
        <el-button @click="gunDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import {useGunForm} from "../composables/useGunForm.js";
import axios from "axios";

export default {
  name: 'PileAddForm',
  emits: ['close', 'refresh'],
  setup(props, {emit}) {
    const {
      openGunDialog,
      gunDialogVisible,
      saveGun,
      removeGun,
      gunForm,
      isAddingGun
    } = useGunForm();

    const addFileList = ref([]);
    // 1. 充电桩表单数据
    const addForm = reactive({
      // 下面字段与 charging_pile 表对应
      id: null,
      pileName: "", // pile_name
      pileCode: "", // pile_code
      pileType: "", // pile_type
      pilePower: null, // pile_power
      pileModel: "", // pile_model
      pileDesc: "", // pile_desc
      suitableVehicle: "", // suitable_vehicle
      pileStatus: "空闲中", // 默认空闲
      stationId: null, // station_id
      pileImgUrl: "", // pile_img_url
      chargingGunCount: 0,
      chargingGuns: [],
    });

    watch(
        () => addForm.chargingGuns,
        (newGuns) => {
          addForm.charchargingGunCountgingPileCount = newGuns.length;
        },
        {deep: true}
    );

    // 上传
    const handleUploadRemove = () => {
      addFileList.value = [];
      addForm.pileImgUrl = "";
    };
    const handleExceed = () => {
      ElMessage.error("只能上传一张图片");
    };
    const handleUploadSuccess = (response) => {
      console.log("response: ", response);
      if (typeof response === 'string') {
        // 后端返回纯文本 URL
        addForm.pileImgUrl = response.trim();
        console.log("addForm.pileImgUrl: ", addForm.pileImgUrl);
        ElMessage.success("图片上传成功");
      } else if (response) {
        // 后端返回 JSON 格式
        addForm.pileImgUrl = response;
        console.log("addForm.pileImgUrl: ", addForm.pileImgUrl);
        ElMessage.success("图片上传成功");
      } else {
        ElMessage.error("上传失败，未返回图片 URL");
      }
    };

    // 取消
    const cancelDialog = () => {
      emit('close');
    };

    // 保存
    const doSave = async () => {
      if (!addForm.pileName.trim() || !addForm.pileCode.trim()) {
        ElMessage.error("请完善站点信息");
        return;
      }

      addForm.enableEvaluation = addForm.enableEvaluation ? 1 : 0;
      addForm.chargingPileCount = addForm.chargingGuns.length;

      try {
        await axios.post("/chargingPile/createChargingPilesWithChargingGun", {
          chargingPile: {...addForm},
          chargingGuns: addForm.chargingGuns,
        });
        ElMessage.success("新增成功");
        emit('refresh'); // 刷新列表
        emit('close');   // 关闭弹窗
      } catch (error) {
        ElMessage.error("新增失败");
      }
    };

    // 取消
    const cancel = () => {
      // 根据实际需求，清空弹窗/重置表单或关闭页面
      emit("cancel");
    };

    return {
      addForm,
      addFileList,
      gunDialogVisible,
      gunForm,
      handleExceed,
      handleUploadSuccess,
      handleUploadRemove,
      cancelDialog,
      openGunDialog,
      isAddingGun,
      saveGun,
      removeGun,
      doSave,
      cancel,
    };
  },
};
</script>

<style scoped>
/* 根据需要自行调整样式 */
</style>
